<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0.minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>ShipsCome 即时通讯</title>
    <link rel="stylesheet" href="../css/layui.mobile.css" />
    <link rel="stylesheet" href="../css/layui.css" />
    <link rel="stylesheet" href="../css/reset.css" />
    <link rel="stylesheet" href="../css/sendFailed.css" />
    <link rel="stylesheet" href="../css/addFriends.css" />
    <link rel="stylesheet" href="../css/upUserinfo.css" />
    <link rel="stylesheet" href="../css/detailChat.css" />
    <link rel="stylesheet" href="../css/friendRequest.css" />
    <link rel="stylesheet" href="../css/detailChat.css" />
    <link rel="stylesheet" href="../css/searchChat.css" />
    <link rel="stylesheet" href="../css/iconfont.css" />
    <link rel="stylesheet" href="../css/swipeDel.css" />
    <link rel="stylesheet" href="../css/record.css" />
    <link rel="stylesheet" href="../css/searchFriend.css" />
</head>

<body>
<script src="../layui.js"></script>
<script src="../js/rem.js"></script>
<script src="../js/reconnecting-websocket.min.js"></script>
<script src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script src="../js/BenzAMRRecorder.min.js"></script>
<script src="../js/zepto.min.js"></script>
<script src="../js/iscroll-lite.js"></script>
<script src="../js/zepto.touchWipe.js"></script>
<script src="../js/BenzAMRRecorder.min.js"></script>
<script src="../js/previewImage.min.js"></script>
<!-- 好友申请模板 -->
<script id="friendRequest" type="text/template">
    <div class="friendRequest">
        <p>好友请求</p>
        <ul>
            {{# layui.each(d.data,function(index,item){ }}
            <li>
                <div class="userBox">
                    <div class="left">
                        <img src={{item.reqAvatar}}>
                    </div>
                    <div class="right">
                        <span>{{item.reqName}}</span>
                        <span>{{item.msg}}</span>
                    </div>

                </div>
                <div class="whether" data-requserid='{{item.reqUserid}}' data-reqid='{{item.reqId}}'>
                    <span data-flag=1>同意</span>
                    <span data-flag=2>拒绝</span>
                </div>
            </li>
            {{# }) }}
        </ul>
    </div>
</script>

<!-- 添加好友模板 -->
<script id="addFriends" type="text/html">
    <div class="addContain">
        <input type="text" class="searchValue" placeholder="请输入昵称或手机号">
        <input type="button" value="搜索" class="searchBtn">
        <div id="view2" style="display:none">
        </div>
    </div>
</script>
<script id="addFriends2" type="text/html">
    {{# layui.each(d,function(index,item){ }}
    <div class="userinfo">
        <div class="userLfet">
            <img src="{{item.l}}">
        </div>
        <div class="userRight">
            <div class="userName">{{item.n}}</div>
            <div class="userPhone">{{item.m}}</div>
        </div>
        <input type="button" data-userId="{{item.i}}" value="添加" class="addBtn">
    </div>
    {{# }) }}
</script>

<!-- 创建群聊好友列表 -->
<script type="text/template" id="friendList">
    <div id="wrapper1" style="width:100%;height:calc(100% - 0.8rem);">
        <ul class="groupFL">
            {{# layui.each(d.data.friend_temp || d.data.friend,function(index,item){ }}
            {{# if(item.conId==1) return }}
            <li>
                <div class="userBox">
                    <img src={{item.avatar || item.logo}}>
                    <span>{{item.username || item.remark || item.name || item.nickname}}</span>
                </div>
                <div class="checkBox" data-userid="{{item.conId || item.id}}"></div>
            </li>
            {{# }) }}
        </ul>
    </div>
    {{# if(d.data.isG){ }}
    <div class="creatChat isG">创建群聊</div>
    {{# } else { }}
    <div class="creatChat isF" layim-event="back_2">确定</div>
    {{#}}}
</script>

<!-- 个人信息展示模板 -->
<script id="userTpl" type="text/template">
    <ul>
        <li class="upAvatar">
            <img src="{{d.data.logo}}" >
        </li>
        <li class="userItem phone"><span>手机</span>{{d.data.mobile}}</li>
        <!-- <li class="userItem upPwd">
            账号与安全
            <i class="layui-icon layui-icon-right"></i>
        </li> -->
        <li class="userItem upNickname">
            <span>昵称</span>
            <!-- onkeyup="this.value=this.value.replace(/\s+/g,'')" -->
            <input type="text" value='{{d.data.nickname}}'>

        </li>
        <li class="userItem upSex">
            <span>性别</span>
            {{# if (d.data.gender == 1) { }}
            <i class="man checked"></i>
            <em>男</em>
            <i class="woman"></i>
            <em>女</em>
            {{# } else { }}
            <i class="man "></i>
            <em>男</em>
            <i class="woman checked"></i>
            <em>女</em>
            {{# } }}
        </li>
        <li class="userItem upSign">
            <span>签名</span>
            <input type="text" value="{{d.data.a}}" placeholder="暂时没有签名~~">
        </li>
        <li class="unbind userItem">解除绑定</li>
        <!-- <li class="clearCache userItem">清除缓存(测试用)</li> -->
    </ul>
</script>
<!-- 查找本地好友模板 -->
<script id="searchTpl" type="text/template">
    <div class="searchFriend">
        <input type="text" placeholder="请输入昵称" class="searchval">
        <div id="friendView"></div>
    </div>
</script>
<script id="findchatTpl3" type="text/template">
    <ul class="chatBox">
        {{# layui.each(d,function(index,item){console.log(item,"---item") }}
        <li data-uid={{item.conId}} data-conid={{item.id}} data-type="friend" data-index="0" class="layim-friend{{item.id}}">
            <div><img src={{item.avatar}}></div>
            <span>{{item.username || item.name}}</span>
            <p>{{item.sign}}</p>
        </li>
        {{# }) }}
    </ul>
</script>
<!-- 选择头像 -->
<script id="checkAvatar" type="text/template">
    <div id="wrapper" style="width:100%;height:calc(100% - 0.8rem)">
        <ul class="imgList">
            {{#  layui.each(d.data, function(index, item){ }}
            <li data-avaId={{index}}>
                <img src="{{item}}" alt="">
                <span class="shadow"></span>
            </li>
            {{#  }); }}
        </ul>
    </div>
    <div class="avaBtn">确定</div>
</script>
<!-- 修改密码模板 -->
<script id="pwdTpl" type="text/template">
    <ul>
        <li class="pwdItem phoneNub">
            <span>手机号</span>
            <div>{{d.data.mobile}}</div>
        </li>
        <li class="pwdItem oldPwd">
            <span>老密码</span>
            <input type="password" value=''>
        </li>
        <li class="pwdItem newPwd">
            <span>新密码</span>
            <input type="password" value=''>
        </li>
        <li class="pwdItem twicePwd">
            <span>重复密码</span>
            <input type="password" value=''>
        </li>
        <li class="pwdItem pwdBtn">
            确定修改
        </li>
    </ul>
    </div>
</script>
<!-- 查看聊天信息模板 -->
<script id="detailChatTpl" type="text/template">
    {{# console.log(d.data,"模板数据") }}
    <ul id="detailChat" >
        <li class="viewUser">
            {{# if(d.data.list.type == 'friend1'){ }}
            <div class='friend clearfloat'>
                <div class='avatar' style="float:left">
                    <img src="{{d.data.list.logo}}">
                </div>
                <div class='info' style="float:left">
                    {{# if(d.data.list.remark && d.data.list.remark.length != 0){ }}
                    <p class="remark">备注:{{d.data.list.remark}}</p>
                    {{# } }}
                    <p class="nickname">昵称:{{d.data.list.nickname}}</p>
                    <p class="phone">手机:{{d.data.list.mobile}}</p>
                    <!-- <p class="phone">手机号</p> -->
                </div>
                <div class="setRemark layui-icon layui-icon-edit">
                    设置备注
                </div>
            </div>
            {{# } else { }}
            <div class="group1">
                <ul class='groupM'>
                    {{# d.data.list.forEach(function(item){ }}
                    <li>
                        <dl>
                            <dt class='avatar'>
                                <img src="{{item.logo}}">
                            </dt>
                            <dd>{{item.remark || item.nickname}}</dd>
                        </dl>
                    </li>
                    {{# }) }}
                    <li class="joinGroup">
                        <img src="https://ifish.intertion.net/images/phon_chat.png">
                    </li>
                    {{# console.log(d.data.qz)}}
                    {{# if(d.data.qz){ }}
                    <li class="exitGroup">
                        <img src="https://ifish.intertion.net/images/minus_chat.png">
                    </li>
                    {{# } }}
                </ul>
            </div>
            {{# } }}
        </li>
        {{# if(!d.data.list.type){ }}
        <li class="layui-icon layui-icon-right" id="up_groupname">修改群名称</li>
        {{# } }}
        <li class="layui-icon layui-icon-right" id='findChat'>查找聊天内容</li>
        <!-- <li>
            置顶聊天
            <div class="switch" id="top" data-flag={{d.data.flag}}>
                <span></span>
            </div>
        </li> -->
        <li>
            屏蔽消息
            <div class="switch" id="nodisturb">
                <span></span>
            </div>
        </li>
        <li class="layui-icon layui-icon-right" id="clearHistory">清空聊天记录</li>
        {{# if(d.data.list.type == "friend1"){ }}
        <li class='delete'>删除好友</li>
        {{# } else if(d.data.qz == false||d.data.qz == true){ }}
        <li class='exitG'>退出群聊</li>
        {{# } }}
    </ul>
</script>

<!-- 搜索聊天历史模板 -->
<script id="findchatTpl1" type="text/template">
    <div class="findChat">
        <input type="text" placeholder="搜索" class="searchChat">
        <div id="view"></div>
    </div>
</script>

<script id="findchatTpl2" type="text/template">
    <ul class="chatBox">
        {{# layui.each(d,function(index,item){ }}
        <li class="chatList">
            <div class="left">
                <img src={{item.avatar}}>
            </div>
            <div class="right">
                <span class="top">{{item.name || item.username}}</span>
                <span class="bottom">{{item.content}}</span>
            </div>
            <div class="date">{{item.timestamp}}</div>
        </li>
        {{# }) }}
    </ul>
</script>
<script>
        $(function () {
            let url = location.href;
            $.ajax({
                url: 'https://ifish.intertion.net/b/wx/getJsSdkTicket',
                type: 'get',
                data: { t: url },
                dataType: 'json',
                success: function (res) {
                    console.log(res);
                    if (typeof res == 'string') {
                        res = JSON.parse(res);
                    }
                    // 微信jdk
                    wx.config({
                        debug: false,
                        appId: 'wx289d1e260a5788ca',
                        timestamp: res.timestamp,
                        nonceStr: res.noncestr,
                        signature: res.signature,
                        jsApiList: ['closeWindow', 'startRecord', 'stopRecord', 'uploadVoice'],
                    });
                },
            });
        });
        //定义初始化数据变量
        const token = '[[${token}]]';
        const ip = 'https://ifish.intertion.net/a';
        const ip2 = 'https://ifish.intertion.net';
        localStorage.setItem('token', token);

        layui.use(['mobile', 'layer', 'laytpl'], function () {
            let mobile = layui.mobile,
                layim = mobile.layim,
                layer = layui.layer,
                laytpl = layui.laytpl;

            if (!localStorage.getItem('req-list')) {
                localStorage.setItem('req-list', '[]');
            }
            // 头像列表
            const avatarList = [];
            for (var i = 0; i < 52; i++) {
                let avatar = `${ip2}/images/${i}.png`;
                avatarList.push(avatar);
            }
            // 获取头像地址
            function getAvatar(avatar) {
                let avatarSrc = ip2 + '/images/' + avatar + '.png';
                return avatarSrc;
            }
            //保存一些以后会用到的全局变量
            var myName,
                myId,
                myAvatar,
                friends, //好友列表
                infoId,
                groups, //群组列表
                storage,
                chatlistId,
                friendId,
                sesstionId,
                isG = false; //判断是否为创建群聊
            var chatHistory = [];
            if (!localStorage.getItem('myMsgId')) {
                localStorage.setItem('myMsgId', '[]');
            }
            let myMsgId = new Array();

            //获取个人资料、好友列表
            var init = function () {
                $.ajax({
                    url: ip + '/w/getWxFriends?t=' + token,
                    type: 'get',
                    async: false,
                    dataType: 'json',
                    success: function (res) {
                        console.log(res);
                        // let data = JSON.parse(res)
                        data = res;
                        console.log(data);
                        myName = data.mine.nickname;
                        myId = data.mine.id;
                        friends = data.friend || [];
                        groups = data.group || [];
                        let avaId = data.mine.avatar;
                        myAvatar = getAvatar(avaId);
                        if (friends.length != 0) {
                            friends[0].list.forEach(function (item, index) {
                                item.avatar = getAvatar(item.avatar);
                            });
                        }
                        if (groups.length != 0) {
                            groups.forEach(function (item, index) {
                                item.avatar = getAvatar(item.avatar);
                            });
                        }
                        if (friends[0]) {
                            friends[0].list.forEach(function (item) {
                                [item.id, item.conId] = [item.conId, item.id];
                            });
                        }
                        console.log('friends', friends);
                        //基础配置
                        layim.config({
                            title: 'ShipsCome',
                            isNewFriend: true,
                            tabIndex: 0,
                            isgroup: true,
                            notice: true,
                            voice: false,
                            copyright: true,
                            chatTitleColor: '#3399ff',
                            init: {
                                mine: {
                                    username: myName,
                                    id: myId,
                                    avatar: myAvatar,
                                },
                                friend: friends,
                                group: groups,
                            },
                            uploadImage: {},
                            uploadFile: {},
                            tool: [
                                {
                                    alias: 'voice',
                                    title: '发送语音',
                                    iconClass: 'icon-yuyin',
                                },
                            ],
                        });
                        console.log(
                            '我的昵称：' + myName + '\n',
                            '我的id：' + myId + '\n',
                            '我的头像：' + myAvatar + '\n'
                        );
                        var headInfo =
                            '<i id="headInfo" class="layui-icon layui-icon-username"></i>';
                        $('.layim-title').append(headInfo);
                        $('#headInfo').css({
                            fontSize: '0.45rem',
                            color: '#fff',
                            position: 'absolute',
                            top: '0',
                            right: '0.3rem',
                        });
                        var searchFriend =
                            '<i id="searchFriend" class="layui-icon layui-icon-search"></i>';
                        $('.layim-title').append(searchFriend);
                        $('#searchFriend').css({
                            fontSize: '0.45rem',
                            color: '#fff',
                            position: 'absolute',
                            top: '0',
                            right: '0.3rem',
                            display: 'none',
                        });
                    },
                });
            };
            // =================================================
            init();

            //监听popstate事件
            var pushHistory = function () {
                var state = {
                    title: "title",
                    url: "#"
                };
                window.history.pushState(state, "title", "#");
            }
            pushHistory();
            window.addEventListener("popstate", function (e) {
                var state = {
                    title: "title",
                    url: "#"
                };
                window.history.pushState(state, "title", "#");
                // e.preventDefault
                console.log("我监听到了浏览器的返回按钮事件啦");
                var back = $(".layim-chat-back");
                var othis = back.last();
                let f1 = function() {
                            return new Promise(function(open) {
                                // console.log(back,"back")
                                // console.log(othis,"f1的othis")
                                var layero = othis.parents('.layui-m-layer').eq(0), //找到有'.layui-m-layer'样式的当前层
                                    index = layero.attr('index'),
                                    PANEL = '.layim-panel';
                                setTimeout(function() {
                                    // layer.close(index);
                                    layero.remove();
                                    $('.layui-layer-move').remove(); //每次后退移除页面上因为layim.msg添加的'.layui-layer-move'元素
                                    $('.layui-layer-prompt').remove();
                                    $('.layui-layer-shade').remove();
                                    //让大图隐藏
                                    $('#__previewImage-container').css('display', 'none');

                                }, 300);
                                othis //给当前层中有'.layim-panel'的元素设置离开动画
                                    .parents(PANEL)
                                    .eq(0)
                                    .removeClass('layui-m-anim-left')
                                    .addClass('layui-m-anim-rout');
                                layero
                                    .prev() //给上一层有'.layim-panel'的元素设置进入动画
                                    .find(PANEL)
                                    .eq(0)
                                    .removeClass('layui-m-anim-lout')
                                    .addClass('layui-m-anim-right');
                                open();
                            });
                        };
                let f2 = () => {
                    back = $('.layim-chat-back');
                    othis = back.last();
                    // console.log(back,"back")
                    // console.log(othis,"f2的othis")
                };
                f1().then(f2);
            }, false);
            //左滑删除
            $('.layim-list-history').touchWipe({ itemDelete: '.delBtn' });
            $('.layim-list-history').on('click', '.delBtn', function (e) {
                let localChat = JSON.parse(localStorage.getItem('layim-mobile'));
                let lid = $(this)
                    .parents()
                    .eq(0)
                    .data('index');
                if (e.target != this) {
                    return false;
                } else {
                    $(this)
                        .parents()
                        .eq(0)
                        .remove();
                    delete layim.cache().message[lid]; //剔除缓存消息
                    //缓存消息为空去掉新消息红点
                    if (JSON.stringify(layim.cache().message) == '{}') {
                        $('#LAY_layimNewMsg').removeClass('layui-show');
                    }
                    delete localChat[myId].history[lid];
                    localStorage.setItem('layim-mobile', JSON.stringify(localChat));
                }
            });
            console.log($('.layim-list-history').children());
            //补零
            var digit = function (num) {
                return num < 10 ? '0' + (num | 0) : num;
            };
            //转换时间
            var formatTime = function (timestamp) {
                var d = new Date(timestamp || new Date());
                return digit(d.getMonth() + 1) + '-' + digit(d.getDate());
            };
            // amr语音解码
            let amr;

            function amrEncode(othis) {
                let that = othis;
                //暂停播放
                if (amr && amr.isPlaying()) {
                    amr.stop();
                    othis.find('i').html('&#xe652;');
                    console.log('暂停播放');
                } else {
                    //初始化
                    amr = new BenzAMRRecorder();
                    let amrFile = othis.data('src');
                    //播放

                    amr.initWithUrl(amrFile).then(function () {
                        if (amr.isInit()) {
                            amr.play();
                            that.find('i').html('&#xe651;');
                            console.log('播放语音');
                        }
                    });
                    //播放完毕
                    amr.onEnded(function () {
                        that.find('i').html('&#xe652;');
                        console.log('播放完毕');
                    });
                }
            }

            // 图片预览
            function bigImg() {
                let imgArr = new Array();
                let chatListBox = $('.layim-chat-main ul');
                let imgList = chatListBox.find('.layui-layim-photos');
                imgList.forEach(function (item) {
                    imgArr.push(item.src);
                });
                $('.layim-chat-main .layim-chat-text').on('click', 'img', function () {
                    console.log($(this).attr('src'));
                    var obj = {
                        urls: imgArr,
                        current: $(this).attr('src'),
                    };
                    previewImage.start(obj);
                });
            }

            // 获取storageKEY，好友id，会话id
            layim.on('chatChange', function (obj) {
                console.log(obj);
                chatlistId = obj.data.type + obj.data.id;
                friendId = obj.data.conId;
                sesstionId = obj.data.id;
                storage = layui.data('layim-mobile');
                if (storage[myId] && storage[myId].chatlog) {
                    chatHistory = storage[myId].chatlog[chatlistId];
                }
                console.log(`
                                    会话id:${sesstionId}
                                    storageKEY:${chatlistId}
                                    好友id:${friendId}
                                    `);
                if (chatHistory) {
                    bigImg();
                }
                // 开始录音
                $('.layim-tool-voice').on('click', function () {
                    if ($(this).hasClass('icon-yuyin')) {
                        $('.layim-chat-send').css('display', 'none');
                        $('.layim-chat-record').css('display', 'flex');
                        $('#bt_recoding').val('按住说话');
                        $(this)
                            .removeClass('icon-yuyin')
                            .addClass('icon-jianpan');
                    } else {
                        $('.layim-chat-send').css('display', 'flex');
                        $('.layim-chat-record').css('display', 'none');
                        $(this)
                            .removeClass('icon-jianpan')
                            .addClass('icon-yuyin');
                    }
                });
                //录音按钮
                var bt_recoding = document.getElementById('bt_recoding');
                //阻止长按复制和弹出菜单
                bt_recoding.addEventListener('contextmenu', function (e) {
                    e.preventDefault();
                });
                // //中间黑色边框和里面的内容（录音状态）
                var blackBoxSpeak = document.querySelector('.blackBoxSpeak');

                // //中间黑色边框和里面的内容（暂停状态）
                var blackBoxPause = document.querySelector('.blackBoxPause');

                //手指移动相关
                var posStart = 0; //初始化起点坐标
                var posEnd = 0; //初始化终点坐标
                var posMove = 0; //初始化滑动坐标

                //录音达到1分钟自动停止
                wx.onVoiceRecordEnd({
                    complete: function (res) {
                        layer.msg('录音时间已超过一分钟');
                        console.log(res);
                        initStatus();
                        wx.uploadVoice({
                            localId: 'res.localId',
                            isShowProgressTips: 0,
                            success: function (res) {
                                var serverId = res.serverId;
                                layim.sendVoice(serverId, rec_time);
                            },
                        });
                    },
                });
                var rec_start, rec_end, rec_time;
                function initEvent() {
                    bt_recoding.addEventListener('touchstart', function (event) {
                        console.log('touchstart');
                        event.preventDefault(); //阻止浏览器默认行为
                        posStart = 0;
                        posStart = event.touches[0].pageY; //获取起点坐标
                        rec_start = new Date().getTime();
                        recordTimer = setTimeout(function () {
                            wx.startRecord({
                                success: function () {
                                    localStorage.rainAllowRecord = 'true';
                                },
                                cancel: function () {
                                    layim.msg('用户拒绝授权录音');
                                },
                            });
                        }, 300);
                        //显示录音 隐藏暂停
                        showBlackBoxSpeak();
                    });
                    bt_recoding.addEventListener('touchmove', function (event) {
                        event.preventDefault(); //阻止浏览器默认行为
                        posMove = event.targetTouches[0].pageY; //获取滑动实时坐标
                        if (posStart - posMove < 200) {
                            //隐藏录音 显示暂停
                            showBlackBoxSpeak();
                        } else {
                            //显示录音 隐藏暂停
                            showBlackBoxPause();
                        }
                    });
                    $(bt_recoding).on('touchend touchcancel', function (event) {
                        console.log('touchend');
                        event.preventDefault(); //阻止浏览器默认行为
                        posEnd = 0;
                        posEnd = event.changedTouches[0].pageY; //获取终点坐标
                        //初始化状态
                        initStatus();
                        rec_end = new Date().getTime();
                        rec_time = rec_end - rec_start;
                        console.log(rec_time);
                        if (rec_time < 1000) {
                            rec_end = 0;
                            rec_start = 0; //小于1000ms，不录音
                            clearTimeout(recordTimer);
                            layer.msg('录音时长小于1秒');
                            var t = setTimeout(function () {
                                wx.stopRecord();
                            }, 800); //这里设置800毫秒，是因为如果用户录音之后马上松开按钮，会成 wx.stopRecord不起作用的情况，然后会一直录音，所以时间设置长一点 //clearTimeout(t);
                        } else {
                            if (posStart - posEnd < 200) {
                                //发送成功
                                showBlackBoxNone();
                                rec_time = Math.ceil(rec_time / 1000);
                                console.log(rec_time);
                                wx.stopRecord({
                                    success: function (res) {
                                        console.log('localId=========>');
                                        console.log(res);
                                        var localId = res.localId;
                                        wx.uploadVoice({
                                            localId: localId, // 需要上传的音频的本地ID，由stopRecord接口获得
                                            isShowProgressTips: 0, // 默认为1，显示进度提示
                                            success: function (res) {
                                                console.log('serverId==========>');
                                                console.log(res);
                                                var serverId = res.serverId; // 返回音频的服务器端ID
                                                layim.sendVoice(serverId, rec_time);
                                            },
                                            fail: function (res) {
                                                console.log('Upload_error==========>');
                                                console.log(res);
                                            },
                                        });
                                    },
                                    fail: function (res) {
                                        console.log('Record_error===========>');
                                        console.log(res);
                                    },
                                });
                            } else {
                                //取消发送
                                showBlackBoxNone();
                                wx.stopRecord();
                            }
                        }
                    });
                }

                initEvent();

                //初始化状态
                var initStatus = function () {
                    bt_recoding.value = '按住 说话';
                    //全部隐藏
                    showBlackBoxNone();
                };

                //显示录音 隐藏暂停
                var showBlackBoxSpeak = function () {
                    bt_recoding.value = '松开 结束';
                    blackBoxSpeak.style.display = 'block';
                    blackBoxPause.style.display = 'none';
                };

                //隐藏录音 显示暂停
                var showBlackBoxPause = function () {
                    bt_recoding.value = '松开手指，取消发送';
                    blackBoxSpeak.style.display = 'none';
                    blackBoxPause.style.display = 'block';
                };

                //隐藏录音
                var showBlackBoxNone = function () {
                    blackBoxSpeak.style.display = 'none';
                    blackBoxPause.style.display = 'none';
                };
                //点击文件
                $('.layim-chat-main')
                    .off('click')
                    .on('click', 'a', function () {
                        var src = $(this).attr('href');
                        console.log(src);
                        var iframe = document.createElement('iframe');
                        iframe.style.display = 'none';
                        iframe.src =
                            'javascript: \'<script>location.href="' + src + '"<\/script>\'';
                        document.getElementsByTagName('body')[0].appendChild(iframe);
                    });
                // 播放语音
                $('.layim-chat-main').on('click', '[layim-event=playAudio]', function () {
                    amrEncode($(this));
                });
            });

            let socket, time;
            function init_socket() {
                // 接入websocket
                socket = new ReconnectingWebSocket('wss://ifish.intertion.net:56666/ws');
                socket.onopen = function (e) {
                    console.log(new Date() + 'WebSocket已连接');
                    socket.send(token);
                    time = setInterval(() => {
                        socket.send('');
                    }, 300);
                };
                socket.onclose = function (e) {
                    clearInterval(time);
                    console.log(new Date() + '连接已关闭');
                };
                // socket通知新消息
                socket.onmessage = function (e) {
                    console.log(e);
                    if (e.data.indexOf('@') != -1) {
                        console.log('接收到消息回执:' + e.data);
                        let res_c = e.data.split('@')[0].split('=')[1];
                        let res_i = e.data.split('@')[1].split('=')[1];
                        //本地所有聊天记录
                        let chat = JSON.parse(localStorage.getItem('layim-mobile'));
                        console.log(chat, '=========>chat')
                        let detailChat = chat[myId].chatlog;
                        console.log(detailChat)
                        for (let key in detailChat) {
                            console.log(key, '=====>key')
                            if (key == `friend${res_c}`) {
                                //遍历与该好友的每一天聊天记录
                                for (let k = 0; k < detailChat[key].length; k++) {
                                    console.log(detailChat[key][k])
                                    if (detailChat[key][k].cid === res_i) {
                                        detailChat[key][k].isSend = true;
                                        console.log(chat);
                                        localStorage.setItem('layim-mobile', JSON.stringify(chat))
                                    }
                                }
                            }
                        }
                        console.log(layim.cache(), '========>layim.cache')

                        if (sesstionId && sesstionId === res_c) {
                            let msgList = $('.layim-chat-main>ul').children('.layim-chat-mine');
                            for (let i = 0; i < msgList.length; i++) {
                                console.log(msgList.eq(i).data('cid'))
                                if (msgList.eq(i).data('cid') === res_i) {
                                    msgList.eq(i).find('.sendStatus>span')
                                        .text('已送达');
                                    break;
                                }
                            }
                        }
                    } else {
                        console.log('接收到消息');
                        getMsg();
                    }
                    //实时聊天图片预览
                    let imgArr = new Array();
                    let chatListBox = $('.layim-chat-main ul');
                    let imgList = chatListBox.find('.layui-layim-photos');
                    imgList.forEach(function (item) {
                        imgArr.push(item.src);
                    });
                    chatListBox.on('click', '.layui-layim-photos', function () {
                        imgArr.push($(this).attr('src'));
                        imgArr = [...new Set(imgArr)];
                        var obj = {
                            urls: imgArr,
                            current: $(this).attr('src'),
                        };
                        previewImage.start(obj);
                    });
                    // 播放语音
                    $('.layim-chat-main').on('click', '[layim-event=playAudio]', function () {
                        amrEncode($(this));
                    });
                };
            }
            init_socket();
            // 对document.hidden做前缀处理
            function getHiddenProp() {
                var prefixes = ['webkit', 'moz', 'ms', 'o'];
                if ('hidden' in document) return 'hidden';
                for (var i = 0; i < prefixes.length; i++) {
                    if (prefixes[i] + 'Hidden' in document) return prefixes[i] + 'Hidden';
                }
                return null;
            }
            // 获取document.visibilityState属性
            function getVisibilityState() {
                var prefixes = ['webkit', 'moz', 'ms', 'o'];
                if ('visibilityState' in document) return 'visibilityState';
                for (var i = 0; i < prefixes.length; i++) {
                    if (prefixes[i] + 'VisibilityState' in document)
                        return prefixes[i] + 'VisibilityState';
                }
                return null;
            }
            // 给document添加事件
            var visProp = getHiddenProp();
            if (visProp) {
                var evtname = visProp.replace(/[H|h]idden/, '') + 'visibilitychange';
                document.addEventListener(
                    evtname,
                    function () {
                        if (document[getVisibilityState()] == 'visible') {
                            init_socket();
                            console.log('前台');
                        } else {
                            socket.close();
                            console.log('后台');
                        }
                    },
                    false
                );
            }
            //请求消息
            function getMsg() {
                console.log('*********调用了getMsg');
                myMsgId = JSON.parse(localStorage.getItem('myMsgId'));
                let username,
                    name,
                    conId,
                    avatar,
                    id,
                    type,
                    content,
                    nickname,
                    nickavatar,
                    ishave = false,
                    firendInfo;
                var msgIndex = localStorage.getItem('x');
                if (!msgIndex) {
                    msgIndex = -1;
                }
                $.ajax({
                    url: ip + '/b/e',
                    data: {
                        t: token,
                        i: msgIndex + '@3',
                    },
                    success: function (res) {
                        console.log(res);
                        // 筛选消息
                        var ms = [];
                        if (res.d) {
                            res.d.filter(function (list, index) {
                                var has = false;
                                myMsgId.forEach(function (item) {
                                    if (list.i == item) {
                                        has = true;
                                    }
                                });
                                if (!has) {
                                    ms.push(list);
                                }
                            });
                        }

                        ms.reverse().forEach(function (item, index) {
                            /* let historyList = $('.layim-list-history').children();
                            historyList.forEach(function(i) {
                                console.log($(i));
                                console.log($(i).data('uid') + '==========' + item.s);
                                if ($(i).data('uid') == item.s && item.ct != 'group') {
                                    $(i).remove();
                                    var cache = layim.cache();
                                    var local = layui.data('layim-mobile')[myId]; //获取当前用户本地数据
                                    delete local.history[$(i).data('index')];
                                    layui.data('layim-mobile', {
                                        key: myId,
                                        value: local,
                                    });
                                }
                            }); */
                            console.log(item);
                            // 同源消息渲染
                            console.log(item.s, myId);
                            if (item.s == myId) {
                                item.m = true;
                                username = myName;
                                console.log('friends', friends[0].list);
                                let list = friends[0].list;
                                for (i of list) {
                                    if (i.id == item.c) {
                                        console.log('i.avatar', i.avatar);
                                        nickavatar = i.avatar;
                                        item.s = i.conId;
                                    }
                                }
                            } else {
                                item.m = false;
                            }
                            //消息索引
                            msgIndex = res.x;
                            localStorage.setItem('x', msgIndex);
                            //区分消息类型
                            switch (item.t) {
                                case '0':
                                    content = item.b;
                                    break;
                                case '1':
                                    content = `img[${ip}/w/b?t=${token}&i=${item.i}]`;
                                    break;
                                case '2':
                                    content = `audio[${ip}/b/l?t=${token}&a=${item.i}]`;
                                    break;
                                case '3':
                                    content = `video[${ip}/b/l?t=${token}&a=${item.i}]`;
                                    break;
                                case '4':
                                    content = `file(${ip}/b/l?t=${token}&a=${item.i})[${
                                        item.b.split('##')[2]
                                        }]`;
                                    break;
                                case '5':
                                    let subStr = item.b.split('##');
                                    let userId = item.s;
                                    if (subStr[0] == 0) {
                                        layim.showNew('List', true);
                                        layim.showNew('Friend', true);
                                        let reqArr = {
                                            [userId]: {
                                                whether: subStr[0],
                                                msg: subStr[1],
                                                reqAvatar: subStr[2],
                                                reqName: subStr[3],
                                                reqId: item.i,
                                            },
                                        };
                                        let x;
                                        let reqlist = localStorage.getItem('req-list');
                                        if (reqlist != '[]') {
                                            JSON.parse(reqlist).forEach(function (item) {
                                                x = Object.keys(item).toString();
                                            });
                                        }
                                        if (!x || x != userId) {
                                            console.log(JSON.parse(reqlist));
                                            reqlist = JSON.parse(reqlist) || [];
                                            reqlist.push(reqArr);
                                            localStorage.setItem(
                                                'req-list',
                                                JSON.stringify(reqlist)
                                            );
                                        }
                                    }
                                    return;
                                case '6':
                                    if (item.ct == 'group') {
                                        layim.addList({
                                            type: 'group',
                                            avatar: ip2 + '/images/group.png',
                                            groupname: item.cn,
                                            id: item.c,
                                        });
                                    } else if (item.ct == 'friend') {
                                        if (item.b.split('##')[0] == '1') {
                                            if (item.s === myId) {
                                                $.ajax({
                                                    url: ip + '/b/a3',
                                                    async: true,
                                                    type: 'get',
                                                    data: { t: token, c: item.c },
                                                    success(res) {
                                                        groupNum = JSON.parse(res);
                                                        groupNum.forEach(function (list) {
                                                            if (list.id != myId) {
                                                                friendInfo = {
                                                                    type: item.ct,
                                                                    avatar: getAvatar(
                                                                        list.logo
                                                                    ),
                                                                    username: list.nickname,
                                                                    groupid: 1,
                                                                    id: item.c,
                                                                    conId: list.id,
                                                                };
                                                                layim.addList(friendInfo);
                                                            }
                                                        });
                                                    },
                                                });
                                            } else {
                                                firendInfo = {
                                                    type: item.ct,
                                                    avatar: getAvatar(
                                                        item.logo || item.ms.split('@')[0]
                                                    ),
                                                    username:
                                                        item.nickName || item.ms.split('@')[1],
                                                    groupid: 1,
                                                    id: item.c,
                                                    conId: item.s,
                                                };
                                                let friendList = $(
                                                    '.layim-list-friend .layui-layim-list'
                                                )
                                                    .eq(1)
                                                    .children();
                                                for (let i = 0; i < friendList.length; i++) {
                                                    if ($(this).data('uid') == item.s) {
                                                        ishave = true;
                                                        break;
                                                    }
                                                }
                                                if (!ishave) layim.addList(firendInfo);
                                            }
                                        }
                                    }
                                    return;
                                case '9':
                                    content = '[不支持类型消息]';
                                    break;
                            }
                            //拿到好友备注
                            conId = item.c;
                            if (!item.m) {
                                friends[0].list.forEach(function (list) {
                                    if (item.s == list.conId) {
                                        //私聊和群聊返回的item.s都是对方个人conId
                                        username = list.username; //根据item.s直接拿到好友备注
                                    } else if (item.c == list.id) {
                                        //群聊返回的item.c是群会话id
                                        console.log('不是同源消息');
                                        avatar = list.avatar;
                                        // name = list.name;
                                    } else {
                                        avatar = getAvatar(item.logo);
                                    }
                                });
                            }
                            if (item.logo)
                                nickavatar = `https://ifish.intertion.net/images/${
                                    item.logo
                                    }.png`;
                            if (item.ct == 'group') {
                                avatar = 'https://ifish.intertion.net/images/group.png';
                            } else {
                                avatar = nickavatar;
                            }
                            let xx = {
                                username: username, //对方备注
                                myAvatar, //自己头像
                                myName, //自己名字
                                id: conId,
                                acceptId: item.a,
                                type: item.ct,
                                mine: item.m,
                                avatar, //群头像
                                name: item.cn, //群名
                                nickname: item.nickName, //对方名字
                                nickavatar, //对方头像
                                conId: item.s, //对方id
                                content: content,
                                cid: item.i,
                            };
                            console.log(xx);

                            layim.getMessage({
                                username: username, //对方昵称
                                avatar: avatar, //自己头像
                                id: conId,
                                acceptId: item.a,
                                type: item.ct,
                                mine: item.m,
                                timestamp: item.st,
                                name: item.cn, //群名
                                nickname: item.nickName, //对方名字
                                nickavatar: `https://ifish.intertion.net/images/${item.logo}.png`, //对方头像
                                conId: item.s,
                                content: content,
                                cid: item.i,
                            });

                            localStorage.setItem('myMsgId', '[]');
                        });
                    },
                });
            }
            getMsg();

            //查看历史消息
            layim.on('chatlog', function (data, ul) {
                let mid =
                    ul
                        .children('li[data-cid]')
                        .eq(0)
                        .data('cid') || '';
                elemChatMain = [
                    '<li data-cid="{{d.cid}}" class="layim-chat-li{{ d.mine ? " layim-chat-mine" : "" }}">',
                    '<div class="layim-chat-user"><img src="{{ d.avatar }}"><cite>',
                    '{{ d.username||d.name||"佚名" }}',
                    '</cite></div>',
                    '<div style="position:relative" class="layim-chat-text"><i class="{{d.cid == "failed"?"icon-xiazaishibai iconfont":""}}"></i><p class="sendStatus" style="display:{{d.mine?"block":"none"}}">{{d.cid == "failed"?"被拒收":"已发送"}}</p>{{ layui.data.content(d.content||"&nbsp;") }}</div>',
                    '</li>',
                ].join('');
                $.ajax({
                    url: ip + '/w/getHistoryRecorde',
                    data: { t: token, cid: sesstionId, mid: mid },
                    dataType: 'json',
                    success: function (res) {
                        res = JSON.parse(res);
                        console.log(res);
                        if (res.length === 0) {
                            layer.msg('暂无更多消息');
                            return;
                        }
                        let chatMainBox = ul.parents('.layim-chat-main')[0];
                        var lastScrollHeight = chatMainBox.scrollHeight;
                        let history_time,
                            history_tpl = '';
                        res.reverse().forEach(function (item) {
                            let content;
                            switch (item.t) {
                                case 0:
                                    content = item.m;
                                    break;
                                case 1:
                                    content = `img[${ip}/w/b?t=${token}&i=${item.i}]`;
                                    break;
                                case 2:
                                    content = `audio[${ip}/b/l?t=${token}&a=${item.i}]`;
                                    break;
                                case 3:
                                    content = `video[${ip}/b/l?t=${token}&a=${item.i}]`;
                                    break;
                                case 4:
                                    content = `file(${ip}/b/l?t=${token}&a=${item.i})[${
                                        item.m.split('##')[2]
                                        }]`;
                                    break;
                                case 9:
                                    content = '[不支持类型消息]';
                                    break;
                            }
                            let data = new Object();
                            (data.cid = item.i),
                                (data.mine = item.s == myId ? true : false),
                                (data.avatar = getAvatar(item.logo)),
                                (data.username = item.nickName),
                                (data.content = content);
                            if (!history_time) {
                                history_time = Number(item.st);
                                history_tpl =
                                    '<li class="layim-chat-system"><span>' +
                                    layui.data.date(Number(item.st)) +
                                    '</span></li>' +
                                    history_tpl;
                            }
                            if (Number(item.st) - history_time > 180 * 1000) {
                                history_tpl +=
                                    '<li class="layim-chat-system"><span>' +
                                    layui.data.date(Number(item.st)) +
                                    '</span></li>';
                                history_time = Number(item.st);
                            }
                            history_tpl += laytpl(elemChatMain).render(data);
                        });
                        ul.prepend(history_tpl);
                        bigImg();
                        console.log(lastScrollHeight, '123');
                        console.log(chatMainBox.scrollHeight);
                        var scrollDiff = chatMainBox.scrollHeight - lastScrollHeight;
                        console.log(scrollDiff);
                        chatMainBox.scrollTop += scrollDiff;
                    },
                });
            });

            $('[lay-type = message]').on('click', function () {
                $('#headInfo').css({
                    display: 'block',
                });
                $('#searchFriend').css({
                    display: 'none',
                });
            });
            $('[lay-type = friend]').on('click', function () {
                $('#headInfo').css({
                    display: 'none',
                });
                $('#searchFriend').css({
                    display: 'block',
                });
            });
            //个人信息修改
            $('#headInfo').on('click', function () {
                let upData = {};
                $.ajax({
                    url: ip + '/b/q?t=' + token + '&reqFrom=wx',
                    async: false,
                    dataType: 'json',
                    success: function (res) {
                        upData = res.d;
                        upData.logo = getAvatar(upData.logo);
                        upData.a = upData.a || '';
                    },
                });
                layim.panel({
                    title: '我的信息',
                    tpl: $('#userTpl').html(),
                    data: upData,
                });
                //修改头像
                $('.upAvatar img').on('click', function () {
                    layim.panel({
                        title: '选择头像',
                        tpl: $('#checkAvatar').html(),
                        data: avatarList,
                    });
                    setTimeout(() => {
                        var myScroll = new IScroll('#wrapper', {
                            mouseWheel: true,
                            scrollbars: true,
                            click: true,
                            taps: true,
                            preventDefault: false,
                        });
                    }, 300);
                    let avatarId;
                    $('.layim-content .imgList li').on('click', function () {
                        $(this)
                            .children('span')
                            .css('visibility', 'visible')
                            .addClass('layui-icon layui-icon-ok');
                        $(this)
                            .siblings()
                            .children('span')
                            .css('visibility', 'hidden');
                        avatarId = $(this).data('avaid');
                    });
                    $('.layim-content .avaBtn').attr('layim-event', 'back');
                    $('.layim-content .avaBtn').on('click', function () {
                        console.log('=====>' + avatarId);
                        $.ajax({
                            url: ip + '/b/n',
                            type: 'post',
                            data: {
                                p: avatarId,
                                t: token,
                            },
                            dataType: 'json',
                            success: function (res) {
                                $('.upAvatar img').attr('src', getAvatar(avatarId));
                                console.log(layim.cache().mine);
                                layim.cache().mine.avatar = getAvatar(avatarId);
                            },
                        });
                    });
                });
                // 修改密码
                $('.layim-content .upPwd').on('click', function () {
                    layim.panel({
                        title: '修改密码',
                        tpl: $('#pwdTpl').html(),
                        data: upData,
                    });
                    // 确定修改
                    $('.layim-content .pwdBtn').on('click', function () {
                        let oldPwd =
                            $('.oldPwd input')
                                .val()
                                .trim() || '';
                        let newPwd =
                            $('.newPwd input')
                                .val()
                                .trim() || '';
                        let twicePwd =
                            $('.twicePwd input')
                                .val()
                                .trim() || '';
                        if (oldPwd == '' || newPwd == '' || twicePwd == '') {
                            layer.msg('不能为空');
                            return;
                        } else if (newPwd != twicePwd) {
                            layer.msg('两次输入的密码不一致');
                            return;
                        }
                        console.log(hex_sha1(oldPwd));
                        $.ajax({
                            url: ip + '/b/s',
                            type: 'post',
                            data: {
                                o: hex_sha1(oldPwd),
                                n: hex_sha1(newPwd),
                                a: upData.mobile,
                                t: token,
                            },
                            success: function (res) {
                                console.log(res);
                                if (res.d === 0) {
                                    $('.oldPwd input')
                                        .val()
                                        .empty();
                                    $('.newPwd input')
                                        .val()
                                        .empty();
                                    $('.twicePwd input')
                                        .val()
                                        .empty();
                                } else {
                                    $('.oldPwd input').attr('type', 'text');
                                    layer.msg('旧密码输入有误！');
                                }
                            },
                        });
                    });
                });
                // 修改昵称
                let oldName = $('.upNickname input').val();
                $('.upNickname input').on('blur', function () {
                    let name = $(this).val().trim();
                    if (name == oldName || name.trim().length == 0) {
                        return;
                    }
                    $.ajax({
                        url: ip + '/b/o',
                        type: 'post',
                        data: {
                            n: name,
                            t: token,
                        },
                        success: function (res) {
                            console.log(res);
                            if (res.d === 0) {
                                layim.cache().mine.username = name;
                                oldName = name;
                            } else if (res.r === -1) {
                                layer.msg('该昵称已被占用');
                                $('.upNickname input').val(oldName);
                            }
                        },
                    });
                });

                // 修改性别
                $('.upSex i').on('click', function () {
                    $(this)
                        .addClass('checked')
                        .siblings('i')
                        .removeClass('checked');
                    let gender;
                    if ($(this).hasClass('man')) {
                        gender = 1;
                    }
                    if ($(this).hasClass('woman')) {
                        gender = 0;
                    }
                    $.ajax({
                        url: ip + '/b/p',
                        data: {
                            g: gender,
                            t: token,
                        },
                        success: function (res) {
                            console.log(res);
                            if (res.d != 0) {
                                layer.msg('修改失败');
                            }
                        },
                    });
                });
                // 修改签名
                let oldSign = $('.upSign input').val();
                $('.upSign input').on('blur', function () {
                    let sign = $(this).val();
                    if (sign == oldSign) {
                        return;
                    }
                    $.ajax({
                        url: ip + '/b/r',
                        type: 'post',
                        data: {
                            a: sign,
                            t: token,
                        },
                        success: function (res) {
                            if (res.d === 0) {
                                $('.upSign input').val(sign);
                            }
                        },
                    });
                });
                //解除绑定
                $('.unbind').on('click', function () {
                    $.ajax({
                        url: ip + '/b/x',
                        type: 'post',
                        data: { t: token },
                        success: function (res) {
                            console.log(res);
                            if (res.r == '0') {
                                window.location.href = 'http://app.intertion.net/login.html';
                            }
                        },
                    });
                });
                // 清空缓存
                $('.clearCache').on('click', function () {
                    localStorage.clear();
                    window.location.reload();
                });
            });

            //模糊查询本地好友
            $('#searchFriend').on('click', function () {
                layim.panel({
                    title: '查找好友',
                    tpl: $('#searchTpl').html(),
                });
                $('.searchval').bind('input propertychange', function () {
                    let keywords = $(this).val();
                    let info = friends[0].list,
                        fillterInfo = new Array();
                    for (let i = 0; i < info.length; i++) {
                        if (
                            (keywords && info[i].username.indexOf(keywords) != -1) ||
                            (keywords && info[i].name.indexOf(keywords) != -1)
                        ) {
                            fillterInfo.push(info[i]);
                        }
                    }
                    if (keywords && fillterInfo.length == 0) {
                        $('#friendView').html(`<em>没有找到相关结果</em>`);
                        return;
                    }
                    let getTpl = findchatTpl3.innerHTML;
                    friendView = document.getElementById('friendView');
                    laytpl(getTpl).render(fillterInfo, function (html) {
                        friendView.innerHTML = html;
                    });
                    $('.chatBox').on('click', 'li', function () {
                        let that = $(this);
                        console.log(that.find('span').text());
                        layim.chat({
                            name: that.find('span').text(),
                            type: 'friend',
                            avatar: that.find('img').attr('src'),
                            id: that.data('conid'),
                        });
                    });
                });
            });
            // 点击新的好友
            layim.on('newFriend', function () {
                $('#LAY_layimNewList').removeClass('layui-show');
                $('#LAY_layimNewFriend').removeClass('layui-show');
                let reqList = JSON.parse(localStorage.getItem('req-list'));

                if (reqList) {
                    reqList.forEach(function (item) {
                        let list = Object.values(item)[0];
                        console.log(list);
                        item.reqAvatar = getAvatar(list.reqAvatar);
                        item.reqName = list.reqName;
                        item.reqId = list.reqId;
                        item.msg = list.msg == 'null' ? '' : list.msg;
                        item.reqUserid = Object.keys(item)[0];
                    });
                    console.log(reqList);
                    layim.panel({
                        title: '新的好友',
                        tpl: $('#friendRequest').html(),
                        data: reqList.reverse(),
                    });
                }
                $('.friendRequest ul').on('click', '.whether>span', function () {
                    let flag,
                        reqid,
                        reqa,
                        reqn,
                        requid,
                        reqcid,
                        ishave = false;
                    flag = $(this).data('flag');
                    reqid = $(this)
                        .parent()
                        .data('reqid');
                    reqa = $(this)
                        .parent()
                        .siblings()
                        .find('img')
                        .attr('src');
                    reqn = $(this)
                        .parent()
                        .siblings()
                        .find('span')
                        .eq(0)
                        .text();
                    requid = $(this)
                        .parent()
                        .data('requserid');

                    function removeStorage(x) {
                        let a, b;
                        a = JSON.parse(localStorage.getItem('req-list'));
                        console.log(a);
                        a.forEach(function (item, index) {
                            b = Object.keys(item)[0];
                            if (b == x) {
                                a.splice(index, 1);
                                localStorage.setItem('req-list', JSON.stringify(a));
                            }
                        });
                    }
                    let requserid = $(this)
                        .parents('.whether')
                        .data('requserid');
                    removeStorage(requserid);
                    $.ajax({
                        url: ip + '/b/j',
                        data: {
                            t: token,
                            a: reqid,
                            b: flag + '@3',
                        },
                        success: res => {
                            console.log(res);
                            reqcid = res.conid;
                            if (res.r == 0) {
                                if ($(this).data('flag') == 2) {
                                    $(this)
                                        .parents('.whether')
                                        .html('<span>已拒绝</span>');
                                } else {
                                    $(this)
                                        .parents('.whether')
                                        .html('<span>已同意</span>');
                                    let friendList = $('.layim-list-friend .layui-layim-list')
                                        .eq(1)
                                        .children();
                                    console.log(friendList);
                                    for (let i = 0; i < friendList.length; i++) {
                                        if (
                                            $(friendList)
                                                .eq(i)
                                                .data('uid') == requid
                                        ) {
                                            ishave = true;
                                            break;
                                        }
                                    }
                                    if (!ishave) {
                                        layim.addList({
                                            type: 'friend',
                                            avatar: reqa,
                                            username: reqn,
                                            groupid: 1,
                                            id: reqcid,
                                            conId: requid,
                                        });
                                    }
                                }
                            } else {
                                $(this)
                                    .parents('.whether')
                                    .html('<span>已同意</span>');
                            }
                        },
                    });
                });
                //添加好友
                var addFriend = '<i id="addFriend" class="layui-icon layui-icon-add-1"></i>';
                $('.layui-m-anim-left .layim-title').append(addFriend);
                $('body')
                    .off('click', '#addFriend')
                    .on('click', '#addFriend', function () {
                        layim.panel({
                            title: '添加好友',
                            tpl: $('#addFriends').html(),
                        });
                        // 搜索好友请求
                        $('.searchBtn').on('click', function () {
                            $('.userinfo').css({
                                display: 'none',
                            });
                            let serarchValue = $('.searchValue')
                                .val()
                                .trim();
                            let userId;
                            if (serarchValue == '') {
                                return;
                            } else {
                                $.ajax({
                                    url: ip + '/b/h',
                                    type: 'get',
                                    data: {
                                        t: token,
                                        a: serarchValue,
                                    },
                                    dataType: 'json',
                                    success: function (res) {
                                        if (
                                            res.r === 0 &&
                                            (res.d && JSON.stringify(res.d) != '[]')
                                        ) {
                                            console.log(res);
                                            for (let i = 0; i < res.d.length; i++) {
                                                res.d[i].l = getAvatar(res.d[i].l);
                                            }
                                            let getTpl = $('#addFriends2').html();
                                            laytpl(getTpl).render(res.d, function (html) {
                                                $('#view2').css({
                                                    display: 'block',
                                                });
                                                $('#view2').html(html);
                                            });
                                        } else {
                                            layer.msg('用户不存在或已是好友');
                                        }
                                    },
                                });
                            }
                            // 添加好友
                            $('body')
                                .off('click', '.addBtn')
                                .on('click', '.addBtn', function () {
                                    let that = $(this);
                                    userId = $(this).data('userid');
                                    console.log(userId);
                                    layer.prompt(
                                        {
                                            formType: 0,
                                            value: '我是' + myName,
                                            title: '请输入验证消息',
                                        },
                                        function (value, index, elem) {
                                            $.ajax({
                                                url: ip + '/b/i',
                                                data: {
                                                    t: token,
                                                    a: userId + '@3',
                                                    b: value,
                                                },
                                                dataType: 'json',
                                                success: function (res) {
                                                    layer.close(index);
                                                    console.log(res);
                                                    if (res.r === 0) {
                                                        that.val('等待验证')
                                                            .attr('disabled', 'disabled')
                                                            .css({
                                                                background: '#c2c2c2',
                                                                'font-size': '12px',
                                                                'margin-top': '14px',
                                                            });
                                                        layer.msg('已发送请求');
                                                    } else if (res.r === -2) {
                                                        $('.addBtn').val('已添加');
                                                        $('.addBtn').off('click');
                                                    }
                                                },
                                            });
                                        }
                                    );
                                });
                        });
                    });
                $('i[layim-event=back]').on('click', function () {
                    $('#addFriend').css('display', 'none');
                });
            });

            //点击群聊
            $('[layim-event=group]').on('click', function () {
                $('body').off('click', '#creatGroup');
                $('body').on('click', '#creatGroup', function () {
                    //在元素创建之后再绑定事件
                    isG = true; //
                    let friend = friends[0] ? friends[0].list : [];
                    console.log(friend);
                    layim.panel({
                        title: '选择联系人',
                        tpl: $('#friendList').html(),
                        data: { friend, isG },
                    });
                    setTimeout(() => {
                        var myScroll1 = new IScroll('#wrapper1', {
                            mouseWheel: true,
                            scrollbars: true,
                            click: true,
                            taps: true,
                            preventDefault: false,
                        });
                    }, 300);
                    //选中用户
                    let idList = [];
                    $('.groupFL li').on('click', function () {
                        console.log(typeof idList);
                        if (typeof idList == 'string') {
                            idList = idList.split(',');
                        }
                        console.log(idList);
                        $(this)
                            .find('.checkBox')
                            .toggleClass('checked');
                        let id = $(this)
                            .find('.checkBox')
                            .data('userid');
                        if (idList.indexOf(id) != -1) {
                            idList.splice(idList.indexOf(id), 1);
                            return;
                        }
                        idList.push(id);
                    });
                    //创建群聊
                    $('body')
                        .off('click', '.isG')
                        .on('click', '.isG', function () {
                            console.log(idList);
                            if (typeof idList != 'string') {
                                console.log('not string');
                                idList = idList.join(',');
                            }
                            console.log(idList);
                            if ($('.checkBox.checked').length < 1) {
                                layer.msg('至少选择一位好友');
                                return;
                            } else {
                                let f1 = function () {
                                    return new Promise(function (open) {
                                        console.log('弹出提示框');
                                        layer.prompt(
                                            {
                                                formType: 0,
                                                value: '',
                                                title: '请输入群名称',
                                            },
                                            function (value, index, elem) {
                                                console.log('发送ajax请求,并关闭提示框');
                                                isG = false;
                                                $.ajax({
                                                    url: ip + '/b/c',
                                                    dataType: 'post',
                                                    data: {
                                                        t: token,
                                                        i: idList,
                                                        n: value,
                                                    },
                                                    success: function (res) {
                                                        res = JSON.parse(res);
                                                        console.log(res);
                                                        if (res.r == 0) {
                                                            isG = false; //
                                                            layim.chat({
                                                                name: value,
                                                                type: 'group',
                                                                avatar:
                                                                    ip2 + '/images/group.png',
                                                                id: res.d,
                                                            });
                                                            layim.addList({
                                                                type: 'group',
                                                                avatar:
                                                                    ip2 + '/images/group.png',
                                                                groupname: value,
                                                                id: res.d,
                                                            });
                                                        }
                                                    },
                                                });
                                            }
                                        );
                                        open();
                                    });
                                };
                                let f2 = () => {
                                    console.log('给确定按钮绑定后退事件');
                                    $('body').off('click', '.layui-layer-btn0');
                                    $('.layui-layer-btn0').attr('layim-event', 'back_p');
                                };
                                f1().then(f2);
                            }
                        });
                });
            });
            // 查看对方信息
            layim.on('detail', function (data) {
                console.log(data, '查看对方信息');
                let friendInfo, groupNum, isQz;
                $.ajax({
                    url: ip + '/b/a3',
                    async: false,
                    type: 'get',
                    data: { t: token, c: data.id },
                    success(res) {
                        groupNum = JSON.parse(res);
                        console.log(groupNum);
                        console.log(myId);
                        groupNum.forEach(function (item) {
                            if (item.id != myId) {
                                friendInfo = item;
                            }
                            console.log(item.qz);
                            item.logo = getAvatar(item.logo);
                            if (item.qz) {
                                item.id == myId ? (isQz = true) : (isQz = false);
                            } else if (!isQz) {
                                isQz = false;
                            }
                        });
                        console.log(isQz);
                    },
                });
                console.log(friendInfo);
                let flag = JSON.parse(localStorage.getItem(data.id)) || 0;
                friendInfo = friendInfo || {};
                friendInfo.type = data.type + '1';
                friendInfo.flag = flag;
                let state;
                $.ajax({
                    url: ip + '/w/f',
                    async: false,
                    data: {
                        t: token,
                        c: sesstionId,
                    },
                    success(res) {
                        state = Boolean(parseInt(res.m));
                    },
                });
                let detailData = friendInfo.type == 'friend1' ? friendInfo : groupNum;
                console.log(detailData, 'detaildata');
                console.log(friendInfo, 'friendInfo');
                layim.panel({
                    title: '聊天详情',
                    tpl: $('#detailChatTpl').html(),
                    data: { qz: isQz, list: detailData },
                });
                //加入群聊
                $('.joinGroup img').on('click', function () {
                    let friend = friends[0].list,
                        friend_temp; //
                    friend_temp = friend.slice(0);
                    for (let i = 0; i < groupNum.length; i++) {
                        for (let j = 0; j < friend_temp.length; j++) {
                            if (
                                groupNum[i].id == friend_temp[j].conId ||
                                friend_temp[j].conId == '1'
                            ) {
                                friend_temp.splice(j, 1);
                                break;
                            }
                        }
                    }
                    console.log(friend_temp);
                    isG = false;
                    layim.panel({
                        title: '拉入群聊',
                        tpl: $('#friendList').html(),
                        data: { friend_temp, isG }, //和$(#creatGroup)内layim.panel设置的data对象里的friend属性保持一致
                    });
                    setTimeout(() => {
                        var myScroll1 = new IScroll('#wrapper1', {
                            mouseWheel: true,
                            scrollbars: true,
                            click: true,
                            taps: true,
                            preventDefault: false,
                        });
                    }, 300);
                    //选中用户
                    let idList = [];
                    $('.groupFL li').on('click', function () {
                        console.log(typeof idList);
                        if (typeof idList == 'string') {
                            idList = idList.split(',');
                        }
                        console.log(idList);
                        $(this)
                            .find('.checkBox')
                            .toggleClass('checked');
                        let id = $(this)
                            .find('.checkBox')
                            .data('userid');
                        if (idList.indexOf(id) != -1) {
                            idList.splice(idList.indexOf(id), 1);
                            return;
                        }
                        idList.push(id);
                    });
                    $('.isF').on('click', function () {
                        //
                        if (idList.length == 0) {
                            return;
                        }
                        idList = idList.join(',');
                        $.ajax({
                            url: ip + '/b/f',
                            type: 'post',
                            data: {
                                t: token,
                                a: sesstionId,
                                b: idList,
                            },
                            success: res => {
                                console.log(res);
                                layer.msg('添加成功');
                            },
                        });
                    });
                });
                // 移出群聊
                $('.exitGroup').on('click', function () {
                    isG = false;
                    let groupNum2 = new Array(),
                        isMe = false;
                    for (let i = 0; i < groupNum.length; i++) {
                        if (groupNum[i].id === myId) {
                            isMe = true;
                            continue;
                        }
                        groupNum2.push(groupNum[i]);
                    }
                    let friend = groupNum2; //
                    console.log(friend);
                    layim.panel({
                        title: '踢出群聊',
                        tpl: $('#friendList').html(),
                        data: { friend, isG }, //和$(#creatGroup)内layim.panel设置的data对象里的friend属性保持一致
                    });
                    setTimeout(() => {
                        var myScroll1 = new IScroll('#wrapper1', {
                            mouseWheel: true,
                            scrollbars: true,
                            click: true,
                            taps: true,
                            preventDefault: false,
                        });
                    }, 300);
                    //选中用户
                    let id = null;
                    $('.groupFL li').on('click', function () {
                        $(this)
                            .siblings()
                            .find('.checkBox')
                            .removeClass('checked');
                        $(this)
                            .find('.checkBox')
                            .toggleClass('checked');
                        id = $(this)
                            .find('.checkBox')
                            .data('userid');
                    });
                    $('.isF').on('click', function () {
                        if (id.length == 0) {
                            return;
                        }
                        $.ajax({
                            url: ip + '/b/g',
                            type: 'post',
                            data: {
                                t: token,
                                a: sesstionId,
                                b: id,
                            },
                            success: res => {
                                layer.msg('踢出成功');
                            },
                        });
                    });
                });
                //设置备注
                $('.setRemark').on('click', function () {
                    let f1 = function () {
                        return new Promise(function (open) {
                            layer.prompt(
                                {
                                    formType: 0,
                                    title: '请输入备注',
                                    maxlength: 8,
                                },
                                function (value, index, elem) {
                                    console.log(data);
                                    $.ajax({
                                        url: ip + '/w/a',
                                        data: {
                                            t: token,
                                            r: value,
                                            f: data.conId,
                                        },
                                        success(res) {
                                            console.log(res);
                                            if (res.r == 0) {
                                                console.log(sesstionId);
                                                console.log(layim.cache().friend[0].list);
                                                layim
                                                    .cache()
                                                    .friend[0].list.forEach(function (item) {
                                                        console.log(item);
                                                        if (item.id == sesstionId) {
                                                            item.username = value;
                                                        }
                                                    });
                                                let arr = layim.cache().friend[0].list;
                                                for (var elem of arr) {
                                                    if (elem.id == data.id) {
                                                        //遍历找到该好友id
                                                        elem.username = value; //修改该好友备注
                                                    }
                                                }
                                                let type =
                                                    data.type == 'friend' ? 'friend' : 'group';
                                                let typeid = type + data.id;
                                                console.log(typeid);
                                                // let his=layim.cache().history[typeid];
                                                // console.log(his);
                                                // his.username=value;
                                                // console.log(his.username);
                                                let d = JSON.parse(
                                                    localStorage.getItem('layim-mobile')
                                                );
                                                if (
                                                    d[myId].history &&
                                                    !$.isEmptyObject(d[myId].history[typeid])
                                                ) {
                                                    console.log(typeid);
                                                    console.log(d[myId].history);
                                                    d[myId].history[typeid].username = value;
                                                    localStorage.setItem(
                                                        'layim-mobile',
                                                        JSON.stringify(d)
                                                    );
                                                }

                                                let $span = $(
                                                    `li[data-conid='${data.id}']>span`
                                                );
                                                console.log(value); //修改后的备注
                                                console.log($span.first().html()); //当前备注
                                                $span.first().html(value); //找到第1个span修改备注
                                                if ($span.length > 2) {
                                                    //若产生聊天记录,页面上会找到4个span
                                                    $span.eq(2).html(value); //找到第3个span修改备注
                                                }
                                            }
                                        },
                                    });
                                }
                            );
                            open();
                        });
                    };
                    let f2 = () => {
                        console.log('给确定按钮绑定后退事件');
                        $('body').off('click', '.layui-layer-btn0');
                        $('.layui-layer-btn0').attr('layim-event', 'back_p');
                        $('.layui-layer-btn0')
                            .parent()
                            .parent()
                            .find('.layui-layer-input')
                            .attr('maxlength', 8);
                    };
                    f1().then(f2);
                });
                if (flag == 1) {
                    $('#top')
                        .children()
                        .addClass('offon');
                    $('#top').addClass('onoff');
                }
                if (state) {
                    $('#nodisturb')
                        .children()
                        .addClass('offon');
                    $('#nodisturb').addClass('onoff');
                }
                //修改群名称
                $('#up_groupname').on('click', function () {
                    let f1 = function () {
                        return new Promise(function (open) {
                            console.log(data);
                            layer.prompt(
                                {
                                    formType: 0,
                                    title: '请输入群名称',
                                    maxlength: 10,
                                },

                                function (value, index, elem) {
                                    $.ajax({
                                        url: ip + '/w/upgn',
                                        data: { t: token, name: value, cid: data.id },
                                        success: function (res) {
                                            console.log(res);
                                            if (res == 0) {
                                                layim.cache().group.forEach(function (item) {
                                                    console.log(item);
                                                    if (item.id == sesstionId) {
                                                        item.groupname = value;
                                                        item.name = value;
                                                    }
                                                });
                                                console.log(layim.cache());

                                                let type =
                                                    data.type == 'friend' ? 'friend' : 'group';
                                                let typeid = type + data.id;
                                                console.log(typeid, 'typeid');
                                                let local = layui.data('layim-mobile')[myId];
                                                if (
                                                    local.history &&
                                                    !$.isEmptyObject(local.history[typeid])
                                                ) {
                                                    local.history[typeid].name = value;
                                                    local.history[typeid].groupname = value;
                                                    layui.data('layim-mobile', {
                                                        key: myId,
                                                        value: local,
                                                    });
                                                }
                                                let $span = $(
                                                    `li[data-conid='${data.id}']>span`
                                                );
                                                console.log(value); //修改后的备注
                                                console.log($span.first().html()); //当前备注
                                                $span.first().html(value); //找到第1个span修改备注
                                                if ($span.length > 2) {
                                                    //若产生聊天记录,页面上会找到4个span
                                                    $span.eq(2).html(value); //找到第3个span修改备注
                                                }
                                            }
                                        },
                                    });
                                }
                            );
                            open();
                        });
                    };
                    let f2 = () => {
                        console.log('给确定按钮绑定后退事件');
                        $('body').off('click', '.layui-layer-btn0');
                        $('.layui-layer-btn0').attr('layim-event', 'back_p');
                        $('.layui-layer-btn0')
                            .parent()
                            .parent()
                            .find('.layui-layer-input')
                            .attr('maxlength', 8);
                    };
                    f1().then(f2);
                });
                // 搜索聊天记录
                $('#findChat').on('click', function () {
                    layim.panel({
                        title: '聊天记录',
                        tpl: $('#findchatTpl1').html(),
                    });
                    chatHistory = JSON.parse(localStorage.getItem('layim-mobile'))[myId]
                        .chatlog[chatlistId];
                    if (chatHistory) {
                        chatHistory.forEach(function (item, index) {
                            item.timestamp = formatTime(item.timestamp);
                        });
                        $('.searchChat').bind('input propertychange', function () {
                            console.log($(this));
                            let chatArr = [];
                            let keywords = $(this).val();
                            chatHistory.forEach(function (item, index) {
                                if (
                                    !item.content ||
                                    item.content.indexOf('img[') != -1 ||
                                    item.content.indexOf('file(') != -1 ||
                                    item.content.indexOf('audio[') != -1
                                ) {
                                    return;
                                }
                                if (keywords && item.content.indexOf(keywords) != -1) {
                                    chatArr.push(item);
                                }
                            });
                            if (keywords && chatArr.length == 0) {
                                $('#view').html(`<em>没有找到相关结果</em>`);
                                return;
                            }
                            let getTpl = findchatTpl2.innerHTML;
                            view = document.getElementById('view');
                            laytpl(getTpl).render(chatArr, function (html) {
                                view.innerHTML = html;
                            });
                        });
                    }
                });
                //会话置顶
                $('#top').on('click', function () {
                    $(this).toggleClass('onoff');
                    $(this)
                        .children()
                        .toggleClass('offon');
                    if ($(this).data('flag') == 0) {
                        $(this).data('flag', 1);
                        localStorage.setItem(data.id, 1);
                    } else {
                        $(this).data('flag', 0);
                        localStorage.setItem(data.id, 0);
                    }
                });
                // 消息免打扰
                $('#nodisturb').on('click', function () {
                    $(this).toggleClass('onoff');
                    $(this)
                        .children()
                        .toggleClass('offon');
                    state = !state;
                    let i;
                    if (state) {
                        i = 1;
                    } else {
                        i = 0;
                    }
                    $.ajax({
                        url: ip + '/b/a1',
                        data: {
                            t: token,
                            c: sesstionId,
                            i: i,
                        },
                        success(res) {
                            console.log(res);
                            if (res.r != 0) {
                            }
                        },
                    });
                });
                // 清空聊天记录
                $('#clearHistory').on('click', function (index) {
                    let chatHistory = JSON.parse(localStorage.getItem('layim-mobile'));
                    layer.confirm(
                        '确定清空聊天记录？',
                        {
                            icon: 3,
                            title: '提示',
                        },
                        function (index) {
                            chatHistory[myId].chatlog[chatlistId] = '';
                            // console.log(chatHistory[myId].history[chatlistId].content);
                            chatHistory[myId].history[chatlistId]
                                ? (chatHistory[myId].history[chatlistId].content = '')
                                : '';
                            localStorage.setItem('layim-mobile', JSON.stringify(chatHistory));
                            $('.layim-chat-main ul').html('');
                            $(`li[data-conid='${data.id}']>p`)
                                .eq(0)
                                .html('');
                            layer.close(index);
                        }
                    );
                });
                //删除好友
                $('.delete').on('click', function () {
                    if (friendId == '1' || friendId == '2') {
                        layer.msg('客服不能删除!');
                    } else {
                        let f1 = function () {
                            return new Promise(function (open) {
                                layer.confirm(
                                    '确定删除好友？',
                                    {
                                        icon: 7,
                                        title: '警告',
                                    },
                                    function (index) {
                                        $.ajax({
                                            url: ip + '/b/a2',
                                            data: {
                                                t: token,
                                                i: friendId,
                                            },
                                            success(res) {
                                                console.log(res);
                                                if (res.r == 0) {
                                                    let historyChatBox = $(
                                                        '.layui-layim .layim-list-history'
                                                    );
                                                    let chatLi = historyChatBox.children('li');
                                                    console.log(chatLi);
                                                    let localChat = JSON.parse(
                                                        localStorage.getItem('layim-mobile')
                                                    );
                                                    console.log(localChat[myId].chatlog);
                                                    chatLi.forEach(function (item) {
                                                        let cid = $(item).data('conid');
                                                        let localFlag = $(item).data('index');
                                                        console.log(cid, sesstionId);
                                                        if (cid == sesstionId) {
                                                            console.log();
                                                            item.remove();
                                                            console.log(
                                                                localChat[myId].chatlog
                                                            );
                                                            delete localChat[myId].chatlog[
                                                                localFlag
                                                            ];
                                                            delete localChat[myId].history[
                                                                localFlag
                                                            ];
                                                            console.log(
                                                                localChat[myId].chatlog
                                                            );
                                                            localStorage.setItem(
                                                                'layim-mobile',
                                                                JSON.stringify(localChat)
                                                            );
                                                            return;
                                                        }
                                                    });
                                                    layim.removeList({
                                                        type: 'friend',
                                                        id: sesstionId,
                                                    });
                                                }
                                            },
                                        });
                                    }
                                );
                                open();
                            });
                        };
                        let f2 = () => {
                            console.log('给确定按钮绑定后退事件');
                            $('body').off('click', '.layui-layer-btn0');
                            $('.layui-layer-btn0').attr('layim-event', 'back_c');
                        };
                        f1().then(f2);
                    }
                });
                //退出群聊
                $('.exitG').on('click', function () {
                    let f1 = function () {
                        return new Promise(function (open) {
                            console.log('fun1');
                            layer.confirm(
                                '确定退出群聊？',
                                {
                                    icon: 7,
                                    title: '警告',
                                },
                                function (index) {
                                    $.ajax({
                                        url: ip + '/b/g',
                                        type: 'post',
                                        data: {
                                            t: token,
                                            a: sesstionId,
                                            b: myId,
                                        },
                                        success: res => {
                                            if (res.r == 0) {
                                                let historyChatBox = $(
                                                    '.layui-layim .layim-list-history'
                                                );
                                                let chatLi = historyChatBox.children('li');
                                                console.log(chatLi);
                                                let localChat = JSON.parse(
                                                    localStorage.getItem('layim-mobile')
                                                );
                                                console.log(localChat[myId].chatlog);
                                                chatLi.forEach(function (item) {
                                                    let cid = $(item).data('conid');
                                                    let localFlag = $(item).data('index');
                                                    console.log(cid, sesstionId);
                                                    if (cid == sesstionId) {
                                                        console.log();
                                                        item.remove();
                                                        console.log(localChat[myId].chatlog);
                                                        delete localChat[myId].chatlog[
                                                            localFlag
                                                        ];
                                                        delete localChat[myId].history[
                                                            localFlag
                                                        ];
                                                        console.log(localChat[myId].chatlog);
                                                        localStorage.setItem(
                                                            'layim-mobile',
                                                            JSON.stringify(localChat)
                                                        );
                                                        return;
                                                    }
                                                });
                                                layim.removeList({
                                                    type: 'group',
                                                    id: sesstionId,
                                                });
                                            }
                                        },
                                    });
                                }
                            );
                            open();
                        });
                    };
                    let f2 = () => {
                        console.log('给确定按钮绑定后退事件');
                        $('body').off('click', '.layui-layer-btn0');
                        $('.layui-layer-btn0').attr('layim-event', 'back_c3');
                    };
                    f1().then(f2);
                });
            });
        });
    </script>
</body>

</html>